package com.cdtu.controller;


import com.cdtu.entity.SysDept;
import com.cdtu.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author : Sakura
 * @Date : 2023/8/8 16:31
 * @Description : TODO 用来接收emp的请求
 */
@Controller
@RequestMapping("/dept")
//解决跨域问题
@CrossOrigin
public class SysDeptController extends BaseController{


    @Autowired
    private SysDeptService deptService;


    @RequestMapping("/list")
    public ModelAndView deptList(ModelAndView modelAndView) {


        List<SysDept> list = deptService.list();
        //返回数据
        modelAndView.addObject("deptList", list);
        //2.跳转页面;
        modelAndView.setViewName("system/sysDept/deptList");
        return modelAndView;
    }

    @RequestMapping("/delete/{deptId}")
    public ModelAndView delete(@PathVariable("deptId") Long deptId, ModelAndView modelAndView) {

        boolean remove = deptService.removeById(deptId);
        modelAndView.setViewName("redirect:/dept/list");
        return modelAndView;
    }

    @RequestMapping("/addDept")
    public ModelAndView addEmpUI(SysDept sysdept, ModelAndView modelAndView) {

        deptService.save(sysdept);
        //2.跳转页面;
        modelAndView.setViewName("redirect:/dept/list");
        return modelAndView;
    }

    @RequestMapping("/toUpdateUI/{deptId}")
    public ModelAndView toUpdateUi(ModelAndView modelAndView,@PathVariable("deptId") Long deptId) {

        SysDept sysDept = deptService.getById(deptId);
        //返回数据
        modelAndView.addObject("sysDept", sysDept);

        getDeptAndDeptList(modelAndView);

        //2.跳转页面;
        modelAndView.setViewName("system/sysDept/updateSysDept");
        return modelAndView;
    }

    @RequestMapping("/toAddUI")
    public ModelAndView toAddSysdept(ModelAndView modelAndView) {

        getDeptAndDeptList(modelAndView);

        //2.跳转页面;
        modelAndView.setViewName("system/sysDept/addSysDept");
        return modelAndView;
    }

    private void getDeptAndDeptList(ModelAndView modelAndView) {
        List<SysDept> list = deptService.list();
        //将部门数据传送到前端给添加人员选择

        //返回数据
        modelAndView.addObject("deptList", list);

        //将角色列表查询出来传送到前端给前端人员选择
        List<SysDept> deptList = deptService.list();
        modelAndView.addObject("deptList", deptList);
    }

    @RequestMapping("/update")
    public ModelAndView update(ModelAndView modelAndView,SysDept sysDept) {
        boolean update = deptService.updateById(sysDept);
        //2.跳转页面;
        modelAndView.setViewName("redirect:/dept/list");
        return modelAndView;
    }
}
